package com.pactera.madp.daemon.quartz.task;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.pactera.madp.common.core.constant.SecurityConstants;
import com.pactera.madp.cp.api.dto.track.BehaviorTrackDto;
import com.pactera.madp.cp.api.feign.RemoteTrackService;
import com.pactera.madp.daemon.quartz.constant.enums.MadpQuartzEnum;
import com.pactera.madp.daemon.quartz.entity.SysJob;
import com.pactera.madp.daemon.quartz.service.SysJobService;
import com.pactera.madp.daemon.quartz.util.TaskUtil;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.quartz.Scheduler;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import static com.pactera.madp.daemon.quartz.constant.enums.MadpQuartzEnum.JOB_STATUS_NOT_RUNNING;

@Slf4j
@Component("behaviorTrackTask")
@AllArgsConstructor
public class BehaviorTrackTask {

    private RemoteTrackService remoteTrackService;
    private SysJobService sysJobService;
    private final TaskUtil taskUtil;
    private final Scheduler scheduler;

    /**
     * 日报数据生成
     * @return
     */
    @SneakyThrows
    public String generateDailyData(String dailyType) {
        log.info("执行日报生成任务...");
        BehaviorTrackDto dto = new BehaviorTrackDto();
        dto.setEvent("dailyData");
        dto.setIsSend(false);
        dto.setDailyType(Integer.valueOf(dailyType));
        remoteTrackService.handTrackInner(dto, SecurityConstants.FROM_IN);
        return MadpQuartzEnum.JOB_LOG_STATUS_SUCCESS.getType();
    }

    /**
     * 日报数据发送
     * @return
     */
    @SneakyThrows
    public String sendDailyData(String dailyType) {
        log.info("执行日报发送任务...");
        BehaviorTrackDto dto = new BehaviorTrackDto();
        dto.setEvent("dailyData");
        dto.setIsSend(true);
        dto.setDailyType(Integer.valueOf(dailyType));
        remoteTrackService.handTrackInner(dto, SecurityConstants.FROM_IN);
        return MadpQuartzEnum.JOB_LOG_STATUS_SUCCESS.getType();
    }

    /**
     * 待办事项提醒发送
     * @param jsonParams
     * {
     *   "wxUserId":"成员企业微信id",
     *   "wxExternalUserid":"外部联系人微信id",
     *   "content":"提醒内容",
     *   "corpId":企业id,
     *   "todoId":代办主键id
     * }
     * @return
     */
    @SneakyThrows
    public String sendTodo(String jsonParams) {
        log.info("执行待办事项提醒任务...");
        BehaviorTrackDto dto = JSONUtil.toBean(jsonParams, BehaviorTrackDto.class);
        dto.setEvent("todo");
        remoteTrackService.handTrackInner(dto, SecurityConstants.FROM_IN);
        return MadpQuartzEnum.JOB_LOG_STATUS_SUCCESS.getType();
    }

    /**
     * 暂停已执行过的待办任务
     * @return
     */
    @SneakyThrows
    public String pauseSendTodo() {
        Calendar nowCal = Calendar.getInstance();
        Calendar cornCal = Calendar.getInstance();
        SimpleDateFormat sdf = new SimpleDateFormat("ss mm HH dd MM yyyy");
        List<SysJob> jobs = sysJobService.list(Wrappers.<SysJob>lambdaQuery()
                .eq(SysJob::getJobStatus, "2")
                .eq(SysJob::getJobGroup, "behaviorTrackTask")
                .eq(SysJob::getMethodName, "sendTodo"));

        for (SysJob sysJob : jobs) {
            String corn = sysJob.getCronExpression();
            int index = corn.lastIndexOf("-");
            index = index > -1 ? index : corn.length();
            corn = corn.substring(0, index).replace("? ", "");
            Date cornDate = sdf.parse(corn);
            cornCal.setTime(cornDate);
            if (cornCal.before(nowCal)) {
                //更新定时任务状态条件，运行状态2更新为暂停状态3
                this.sysJobService.updateById(SysJob.builder().jobId(sysJob.getJobId())
                        .jobStatus(JOB_STATUS_NOT_RUNNING.getType()).build());
                taskUtil.pauseJob(sysJob, scheduler);
            }
        }

        return MadpQuartzEnum.JOB_LOG_STATUS_SUCCESS.getType();
    }

}
